package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Score;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import sun.security.pkcs11.wrapper.CK_VERSION;

import java.util.List;
import java.util.TreeMap;

@Service(version = "1.0.0")
public class ScoreApiImpl implements ScoreApi{

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public String save(Score score) {
        if(score.getUserId() == null){
            return "保存失败";
        }
        this.mongoTemplate.save(score);
        return "保存成功";
    }

    @Override
    public TreeMap<String, Integer> selectByUserId(Integer userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        List<Score> scores = mongoTemplate.find(query, Score.class);
        if( scores == null ){
            return null;
        }

        TreeMap<String, Integer> results=new TreeMap<>();
        for (Score score : scores) {
                results.put(score.getLevel(),score.getScore());
        }

        return  results;
    }

    //TODO 2020-12-16 01:53:17
    @Override
    public void updateByUserIdAndLevel(Score score, Long id, String level) {
        Criteria criteria = Criteria.where("userId").is(id).and("level").is(level);
        Query query = Query.query(criteria);
        Update update = Update.update("score", score.getScore());
        Update update1 = Update.update("character", score.getCharacter());
        this.mongoTemplate.upsert(query, update, Score.class);
        this.mongoTemplate.upsert(query, update1, Score.class);
    }


}
